package com.behome.socket_proxy.netty_D.client;

import com.behome.socket_proxy.netty_D.server.StandardDNettyServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyClient {

    public String HOST;
    public int PORT;
    public EventLoopGroup group;
    public Bootstrap bootstrap;
    public ChannelHandlerContext clientCtx;

    private Channel channel;

    public NettyClient(ChannelHandlerContext ctx, String host, int port) {
        this.HOST = host;
        this.PORT = port;
        this.clientCtx = ctx;
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) {
                ChannelPipeline pipeline = ch.pipeline();
//                pipeline.addLast(new LengthFieldBasedFrameDecoder(8192, 10, 2, -12, 0));
                pipeline.addLast("decoder", new ByteArrayDecoder());
                pipeline.addLast("encoder", new ByteArrayEncoder());
                pipeline.addLast(new IdleStateHandler(0, 1, 0));
                pipeline.addLast(new ProxyCilentHandler());
            }
        });
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    }

    //连接端口
    public Channel getChannel() {
        if (channel == null) {
//            group.shutdownGracefully();
            try {
                channel = bootstrap.connect(HOST, PORT).sync().channel();
                log.info("往CMD 已经在" + HOST + "的" + PORT + "端口建立Channel");
            } catch (Exception e) {
                log.error("适配器未连接上:" + e.getMessage());
                return null;
            }
        } else if (!channel.isActive()) {
            try {
                channel = bootstrap.connect(HOST, PORT).sync().channel();
                log.info("存活失效重新" + HOST + "的" + PORT + "端口建立Channel");
            } catch (Exception e) {
                log.error("适配器未连接上:" + e.getMessage());
                return null;
            }
        }
        return channel;
    }

}
